<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
      <BasicForm @register="registerForm" ref="formRef">
          <template #deptIdSlot="{model,field}">
              <JSelectDept v-model:value="model[field]" @change="DeptChange" :multiple="false"></JSelectDept>
          </template>
          <template #personIdSlot="{model,field}">
              <JSelectDormPerson v-model:value="model[field]" :departmentId="deptId"></JSelectDormPerson>
          </template>
      </BasicForm>
  <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="学生心理健康排查异常学生信息" key="dormMentalTsAbnormal" :forceRender="true">
        <a-button type="primary" style="margin-bottom:10px;" @click="handleOpenAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <JVxeTable
          keep-source
          resizable
          ref="dormMentalTsAbnormal"
          :loading="dormMentalTsAbnormalTable.loading"
          :columns="dormMentalTsAbnormalTable.columns"
          :dataSource="dormMentalTsAbnormalTable.dataSource"
          :height="340"
          :rowNumber="true"
          :rowSelection="false"
          :disabled="formDisabled"
          :toolbar="false"
          :toolbarConfig="{ btn: ['',]}"
          ></JVxeTable>
      </a-tab-pane>
    </a-tabs>
    <!-- <PersonSelectModal @register="regModal" :params="params" @getSelectResult="setValue" v-bind="getBindValue" ></PersonSelectModal> -->
    <PersonListSelect :params="params" @register="regModal" @getSelectResult="setValue" v-bind="getBindValue" ></PersonListSelect>

  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref,reactive} from 'vue';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import { JVxeTable } from '/@/components/jeecg/JVxeTable'
    import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts'
    import {formSchema,dormMentalTsAbnormalColumns} from '../DormMentalTs.data';
    import {saveOrUpdate,dormMentalTsAbnormalList,selectPersonList} from '../DormMentalTs.api';
    import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils'
    import JSelectDormPerson from '@/components/Form/src/jeecg/components/JSelectDormPerson.vue'
    import JSelectDept from '@/components/Form/src/jeecg/components/JSelectDept.vue'
    import { useModal } from '/@/components/Modal';
    // import PersonSelectModal from '@/components/Form/src/jeecg/components/modal/PersonSelectModal.vue'
    import PersonListSelect from './PersonListSelect.vue';

    const [regModal, { openModal }] = useModal();

    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const formDisabled = ref(false);
    const refKeys = ref(['dormMentalTsAbnormal', ]);
    const activeKey = ref('dormMentalTsAbnormal');
    const dormMentalTsAbnormal = ref();
    const tableRefs = {dormMentalTsAbnormal, };
    const dormMentalTsAbnormalTable = reactive({
          loading: false,
          dataSource: [],
          columns:dormMentalTsAbnormalColumns
    })
    let deptId = ref('')
    let params = ref({
      departmentId:''
    })
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });
     //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await reset();
        setModalProps({confirmLoading: false,showCancelBtn:data?.showFooter,showOkBtn:data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        formDisabled.value = !data?.showFooter;
        if (unref(isUpdate)) {
            deptId.value =  data.record.deptId 
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
             requestSubTableData(dormMentalTsAbnormalList, {id:data?.record?.id}, dormMentalTsAbnormalTable)
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //方法配置
    const [handleChangeTabs,handleSubmit,requestSubTableData,formRef] = useJvxeMethod(requestAddOrEdit,classifyIntoFormData,tableRefs,activeKey,refKeys);

      function handleOpenAdd() {
        params.value.departmentId =  deptId.value
        openModal(true, {
          isUpdate: false,
        });
      }

    function DeptChange(e){
      console.log(e);
      deptId.value = e? e.join(','): ''
    }

function setValue(options, values) {
        // selectOptions.value = options;
        //emitData.value = values.join(",");
        let value = values.join(",")
        console.log(value);
        if(value){
          selectPersonList({
            id: value
          }).then(res=>{
            res.records.forEach(item => {
              let data = {
                personId: item.id,
                personName: item.name,
                personCode: item.code,
              }
              // dormMentalTsAbnormalTable.dataSource.push(data)
              // console.log(tableRefs.dormMentalTsAbnormal.value);
              tableRefs.dormMentalTsAbnormal.value.addRows([data])
              // console.log(dormMentalTsAbnormalTable.dataSource);

            });
          })
        }
        // emit('update:value', values.join(','));
        //update-begin-author:liusq date:20230517 for:选择职务组件v-model方式绑定值不生效

  }
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

    async function reset(){
      await resetFields();
      activeKey.value = 'dormMentalTsAbnormal';
      dormMentalTsAbnormalTable.dataSource = [];
    }
    function classifyIntoFormData(allValues) {
         let main = Object.assign({}, allValues.formValue)
         return {
           ...main, // 展开
           dormMentalTsAbnormalList: allValues.tablesValue[0].tableData,
         }
       }
    //表单提交事件
    async function requestAddOrEdit(values) {
        try {
            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(values, isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
    :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>